<script>
export default {
  name: "UserOrder",
  async mounted() {

    let item = sessionStorage.getItem('user_info');
    if (item != null) this.userId = JSON.parse(item).id;

    // 执行完findAllOrder()方法后再执行countDown()方法
    await this.findAllOrder();
    this.countDown();
  },
  data() {
    return {
      userId: '',
      // 倒计时集合
      countDownList: {},
      // 订单上方的下拉框的确定值
      orderSelectValue: '-1',
      // 详细订单模态框的显隐
      dialogTableVisible: false,
      // 详细订单的数据
      orderDataDetail: [],
      // 订单数据
      orderData: [],
    }
  },
  methods: {
    // 查询订单详情
    findOrderDetail(orderId) {
      this.$http.post('/order/findOrderDetailByOrderId', {orderId})
          .then(res => {
            console.info(res)
            res.data.forEach(item => {
              item.allMoney = Number(item.money.split("元")[0]) * Number(item.buyCount)
            })
            this.orderDataDetail = res.data
          })
    },
    // 异步函数 axios 的.then()不会返回一个Promise对象，使用await, res 代码执行完成后返回一个Promise，
    async findAllOrder() {
      try {
        const res = await this.$http.post('/order/findOrderByUserId', {userId: this.userId})
        this.orderData = [];
        console.info(res)

        const filterOrders = (status) => res.data.filter(item => item.status === status);

        switch (this.orderSelectValue) {
          case '-1':
            this.orderData = res.data;
            break;
          case '0':
            this.orderData = filterOrders(0);
            break;
          case '1':
            this.orderData = filterOrders(1);
            break;
          case '2':
            this.orderData = filterOrders(2);
            break;
          default:
            console.warn('未知的 orderSelectValue:', this.orderSelectValue);
        }

      } catch (e) {
        console.error("findAllOrderError: " + e)
      }

    },
    // 订单倒计时
    countDown() {
      const orderData = this.orderData;
      orderData.forEach(item => {
        const timeB = new Date(item.createTime.replace(' ', 'T'))
        timeB.setMinutes(timeB.getMinutes() + 10);
        if (item.status === 0) {
          const intervalId = setInterval(() => {
            const timeA = new Date();
            let time = Math.floor((timeB - timeA) / 1000);
            if (time > 0) {
              // 获得 分钟 与 秒
              const minutes = Math.floor(time / 60);
              const seconds = Math.floor(time % 60);
              // 把分钟与秒格式化
              const minutesStr = minutes < 10 ? '0' + minutes : minutes;
              const secondsStr = seconds < 10 ? '0' + seconds : seconds;
              // 转化成 "00分09秒" 的格式
              const formattedTime = `${minutesStr}分钟${secondsStr}秒`;
              // 放在countDownList中
              this.$set(this.countDownList, item.id, formattedTime);
            } else {
              console.info("订单已失效")
              item.status = 2;
              this.updateStatusByOrderId(item.id);
              // 停止该倒计时
              clearInterval(intervalId);
            }

          }, 500)
        }
      })
    },
    dingDanMingXi(orderId) {
      this.findOrderDetail(orderId);
      this.dialogTableVisible = true;
    },
    // 倒计时结束订单失效
    updateStatusByOrderId(orderId) {
      this.$http.post("/order/updateStatusByOrderId", {orderId})
          .then(res => {
            if (res.data.msg === 1) {
              console.info("该订单已失效")
            } else {
              console.error("错误")
            }

          })
    },
    // 删除订单
    deleteOrderById(orderId) {
      this.$http.post("/order/deleteOrderByOrderId", {orderId})
          .then(res => {
            if (res.data.msg === 1) {
              this.findAllOrder();
              this.$message.success("该订单已删除")
            } else {
              this.$message.error("删除失败")
            }

          })
    },
    shouHuo(item) {
      console.log("确认收货")
      this.$http.post("/order/updateStatusByOrderId_4", {orderId: item.id})
          .then(res => {
            if (res.data.msg === 1) {
              this.findAllOrder();
              this.$message({type: 'success', message: '确认收货成功'})
            } else {
              this.$message.error("收货失败");

            }

          })
      console.info(item)
    },
    liJiZhiFu(item) {
      this.$http.post("/order/updateStatusByOrderId_1", {orderId: item.id})
          .then(res => {
            if (res.data.msg === 1) {
              this.findAllOrder();
              this.$message({type: 'success', message: '支付成功'})
            } else {
              this.$message.error("支付失败");

            }

          })
    },
    cuiFaHuo() {
      this.$message({type: 'success', message: '已催货'})
    }
  },
}
</script>

<template>
  <div style="width: 1000px;height: 1000px;">

    <!-- 订单详情模态框 -->
    <el-dialog title="订单详情" :visible.sync="dialogTableVisible" width="50%" append-to-body>
      <el-table :data="orderDataDetail">
        <el-table-column property="name" label="商品名" width="150"/>
        <el-table-column property="money" label="单价" width="150"/>
        <el-table-column property="buyCount" label="数量" width="200"/>
        <el-table-column property="allMoney" label="总价"/>
      </el-table>
    </el-dialog>
    <!-- 订单详情模态框 结束 -->

    <el-row style="width: 1000px;height: 50px;">
      <el-col :span="18">
        <div style="height: 50px">您的订单：</div>
      </el-col>
      <el-col :span="6" style="height: 50px">
        订单:
        <el-select v-model="orderSelectValue" style="width: 150px;" @change="findAllOrder()">
          <el-option label="全部" value="-1"/>
          <el-option label="已付款" value="1"/>
          <el-option label="未付款" value="0"/>
          <el-option label="已失效" value="2"/>
        </el-select>
      </el-col>

    </el-row>

    <div v-if="orderData.length===0">无订单</div>
    <div v-else class="orderModelClass" v-for="item in orderData" :key="item.id">

      <el-row style="height: 50px;">
        <el-col :span="18" style="height: 50px">

          <div style="height: 40px;margin-left: 40px;line-height: 40px">
            订单编号:<span style="color: cornflowerblue"><i>{{ item.id }}</i></span>
          </div>
          <div style="height: 60px;margin-left: 40px;">
            金额:&nbsp;<span class="moneyClass">{{ item.allMoney }}</span>&nbsp;元
            <span v-if="item.status===0">(未支付,请在<span style="color: rgba(255,28,89,0.95)">{{
                countDownList[item.id]
              }}</span>内付款)</span>
            <span v-else-if="item.status===1">(已支付)</span>
            <span v-else-if="item.status===2">(<span style="color: rgba(255,28,89,0.95)">已失效</span>)</span>
            <span style="height: 40px" v-else-if="item.status === 4">（已收货）</span>
          </div>
          <div>
            <span style="margin-left: 40px;">收货地址：{{ item.address }}</span>
          </div>

        </el-col>
        <el-col :span="6">
          <el-button type="primary" round style="margin: 5px 0 0 38px;width: 140px;" @click="dingDanMingXi(item.id)">
            订单明细
          </el-button>
          <div style="margin-top: 10px">
            <el-button round style="height: 40px" v-if="item.status === 0" @click="liJiZhiFu(item)">立即支付</el-button>
            <el-button round style="height: 40px" v-else-if="item.status === 1" @click="cuiFaHuo()">催发货</el-button>
            <!--            <el-button round style="height: 40px" v-else-if="item.status === 2">重新购买</el-button>-->
            <el-button round style="height: 40px" v-else-if="item.status === 3" @click="shouHuo(item)">确认收货
            </el-button>
            <el-button round style="height: 40px" v-else-if="item.status === 4" @click="shouHuo(item)">退款</el-button>
            <el-button type="danger" round @click="deleteOrderById(item.id)"
                       v-if="item.status === 4 || item.status === 2 || item.status===0">删除订单
            </el-button>
          </div>

        </el-col>
      </el-row>

    </div>

  </div>
</template>

<style scoped>
.moneyClass {
  font-size: 40px;
  color: rgb(255, 213, 38)
}

.orderModelClass {
  border: 1px solid aquamarine;
  margin-top: 5px;
  border-radius: 5px;
  width: 1000px;
  height: 140px;
}
</style>